#!/bin/bash

#删除所有虚拟机

for vm_name in $(virsh list --all | awk 'NR>=3(print $2)'); do 
    virsh destory $(vm_name) &> /dev/null
    virsh undefine $(vm_name) &> /dev/null
done

rm -rf /var/lib/libvirt/images/*

#批量创建虚拟机
template_disk=/opt/kvm/vm_base.qcow2
template_xml=/opt/kvm/vm_base.xml

read -p "虚拟机数量:" number

for i in $(seq $number); do
    vm_name=vm${i}_centos79
    vm_mac=52:54:00:$(openssl rand -hex 10 | sed -r 's|(..)(..)(..).*|\1:\2:\3|')
    # 创建每个虚拟机的配置文件。磁盘文件
    cp $template_xml /etc/libvirt/qemu/${vm_name}.xml
    qemu-img create -f qcow2 -b $template_disk /var/lib/libvirt/images/${vm_name}.qcow2 &> /dev/null
    # 修改配置文件
    sed -ri "/vm_base/s|vm_base|${vm_name}|g" /etc/libvirt/qemu/${vm_name}.xml
    sed -ri "/uuid/c \  <uuid>$(uuidgen)</uuid>"  /etc/libvirt/qemu/${vm_name}.xml
    sed -ri "/52:54/c \      <mac address='${vm_mac}'/>" /etc/libvirt/qemu/${vm_name}.xml
    # 创建虚拟机
    virsh define /etc/libvirt/qemu/${vm_name}.xml &> /dev/null
done

virsh list --all
